package database

import (
	"alfred/models"
	"time"
)

// CreateAction 创建Action
func (db *DB) CreateAction(action *models.Action) error {
	action.ID = models.NewID()
	action.CreatedAt = time.Now()
	action.UpdatedAt = time.Now()

	return db.Create(action).Error
}

// GetAction 获取Action
func (db *DB) GetAction(id string) (*models.Action, error) {
	var action models.Action
	err := db.First(&action, "id = ?", id).Error
	if err != nil {
		return nil, err
	}
	return &action, nil
}

// GetActionsByNodeID 根据NodeID获取所有Action
func (db *DB) GetActionsByNodeID(nodeID string) ([]*models.Action, error) {
	var actions []*models.Action
	err := db.Where("node_id = ?", nodeID).Order("\"order\"").Find(&actions).Error
	return actions, err
}

// ListActions 获取所有Action
func (db *DB) ListActions() ([]*models.Action, error) {
	var actions []*models.Action
	err := db.Order("created_at DESC").Find(&actions).Error
	return actions, err
}

// UpdateAction 更新Action
func (db *DB) UpdateAction(action *models.Action) error {
	action.UpdatedAt = time.Now()
	return db.Save(action).Error
}

// DeleteAction 删除Action
func (db *DB) DeleteAction(id string) error {
	return db.Delete(&models.Action{}, "id = ?", id).Error
}